<!DOCTYPE html>
<html>
<head hexo-theme='https://volantis.js.org/#2.6.6'>
  <meta charset="utf-8">
  <!-- SEO相关 -->
  
    
  
  <!-- 渲染优化 -->
  <meta name="renderer" content="webkit">
  <meta name="force-rendering" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="HandheldFriendly" content="True" >
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <!-- 页面元数据 -->
  
    <title>C++程序设计基础(4) - 复合类型数据：数组 - Jun&#39;s Blog</title>
  
    <meta name="keywords" content="C++">
  
  
    <meta name="description" content="介绍数组和C风格字符串的处理, 以及一些十分常用的数组算法.">
  

  <!-- feed -->
  
    <link rel="alternate" href="/junblog/atom.xml" title="Jun's Blog">
  

  <!-- import meta -->
  

  <!-- link -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.13/css/all.min.css">
  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css">

  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.css">

  

  
  <link rel="shortcut icon" type='image/x-icon' href="https://cdn.jsdelivr.net/gh/xaoxuu/assets@master/favicon/favicon.ico">
  

  

  

  <!-- import link -->
  

  
  
    
<link rel="stylesheet" href="/junblog/css/style.css">

  

  <script>
    function setLoadingBarProgress(num) {
      document.getElementById('loading-bar').style.width=num+"%";
    }
  </script>

  
  
</head>

<body>
  
  <div id="loading-bar-wrapper">
  <div id="loading-bar"></div>
</div>
<header class="l_header shadow blur">
  <div class='container'>
  <div class='wrapper'>
    <div class='nav-sub'>
      <p class="title"></p>
      <ul class='switcher nav-list-h'>
        <li><a class="s-comment fas fa-comments fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
          <li><a class="s-toc fas fa-list fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
      </ul>
    </div>
		<div class="nav-main">
      
        
        <a class="title flat-box" target="_self" href='/junblog/'>
          
          
          
            Jun's Blog
          
          
        </a>
      

			<div class='menu navigation'>
				<ul class='nav-list-h'>
          
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/
                  
                  
                  
                    id="junblog"
                  >
                  <i class='fas fa-rss fa-fw'></i>首页
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/categories/
                  
                  
                  
                    id="junblogcategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/tags/
                  
                  
                  
                    id="junblogtags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/archives/
                  
                  
                  
                    id="junblogarchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/friends/
                  
                  
                  
                    id="junblogfriends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="flat-box" href=/junblog/aboutme/
                  
                  
                  
                    id="junblogaboutme"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
              </li>
            
          
          
				</ul>
			</div>

      <div class="m_search">
        <form name="searchform" class="form u-search-form">
          <i class="icon fas fa-search fa-fw"></i>
          <input type="text" class="input u-search-input" placeholder="Search..." />
        </form>
      </div>

			<ul class='switcher nav-list-h'>
				
					<li><a class="s-search fas fa-search fa-fw" target="_self" href='javascript:void(0)'></a></li>
				
				<li>
          <a class="s-menu fas fa-bars fa-fw" target="_self" href='javascript:void(0)'></a>
          <ul class="menu-phone list-v navigation white-box">
            
              
            
              <li>
                <a class="flat-box" href=/junblog/
                  
                  
                  
                    id="junblog"
                  >
                  <i class='fas fa-rss fa-fw'></i>首页
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/categories/
                  
                  
                  
                    id="junblogcategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/tags/
                  
                  
                  
                    id="junblogtags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/archives/
                  
                  
                  
                    id="junblogarchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/friends/
                  
                  
                  
                    id="junblogfriends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="flat-box" href=/junblog/aboutme/
                  
                  
                  
                    id="junblogaboutme"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
              </li>
            
          
            
          </ul>
        </li>
			</ul>
		</div>
	</div>
  </div>
</header>

<script>setLoadingBarProgress(40);</script>



  <div class="l_body nocover">
    <div class='body-wrapper'>
      

<div class='l_main'>
  

  
    <article id="post" class="post white-box reveal blur article-type-post" itemscope itemprop="blogPost">
      


  <section class='meta'>
    
      
      
      <div class="meta" id="header-meta">
        
          
  <h1 class="title">
    <a href="/junblog/2020/08/16/C++%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E5%9F%BA%E7%A1%80(4)%20-%20%E5%A4%8D%E5%90%88%E7%B1%BB%E5%9E%8B%E6%95%B0%E6%8D%AE_%E6%95%B0%E7%BB%84/">
      C++程序设计基础(4) - 复合类型数据：数组
    </a>
  </h1>


        
        <div class='new-meta-box'>
          
            
          
            
              
<div class='new-meta-item author'>
  <a href="" rel="nofollow">
    <img src="https://cdn.jsdelivr.net/gh/JunyuanHe/cdn-assets@master/img/GeographicObjects2.jpg">
    <p>Jun</p>
  </a>
</div>

            
          
            
              
  
  <div class='new-meta-item category'>
    <a href='/junblog/categories/%E8%AE%A1%E7%AE%97%E6%9C%BA/C/' rel="nofollow">
      <i class="fas fa-folder-open fa-fw" aria-hidden="true"></i>
      <p>计算机/C++</p>
    </a>
  </div>


            
          
            
              <div class="new-meta-item date">
  <a class='notlink'>
    <i class="fas fa-calendar-alt fa-fw" aria-hidden="true"></i>
    <p>发布于：2020年8月16日 22:02</p>
  </a>
</div>

            
          
            
              

            
          
        </div>
        
          <hr>
        
      </div>
    
  </section>


      <section class="article typo">
        <div class="article-entry" itemprop="articleBody">
          
          
          <p>介绍数组和C风格字符串的处理, 以及一些十分常用的数组算法.</p>
<a id="more"></a>
<h2 id="一维数组">一维数组</h2>
<p><strong>• 数组的定义:</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a[<span class="number">10</span>]; <span class="keyword">double</span> b[<span class="number">20</span>]; <span class="keyword">char</span> c[<span class="number">80</span>];</span><br></pre></td></tr></table></figure>
<p>数组的大小必须是正的整数类型的常量表达式.</p>
<p><strong>• 一维数组赋初值:</strong></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a[<span class="number">5</span>] = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>&#125;; </span><br><span class="line"><span class="keyword">int</span> a1[] = &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>&#125;;</span><br><span class="line"><span class="keyword">int</span> a2[<span class="number">5</span>] = &#123;<span class="number">1</span>&#125;; <span class="comment">//后面默认初值为0</span></span><br></pre></td></tr></table></figure>
<p>注意: 如果数组未赋初值, 则数组中元素的值是不确定的(有的编译器会清为特定的值, 有的编译器保留残留值)</p>
<p><strong>• 计算数组元素个数:</strong> <code>sizeof(a)/sizeof(a[0])</code></p>
<h2 id="多维数组">多维数组</h2>
<p><strong>• 多维数组的定义:</strong> <code>int a[2][3][4];</code></p>
<p><strong>• 多维数组在内存中的存储:</strong> 按<code>a[0][0][0], a[0][0][1], a[0][0][2], a[0][0][3], a[0][1][0], a[0][1][1], a[0][1][2], a[0][1][3], a[0][2][0], ...</code> 依次存放, 占据连续空间</p>
<p><strong>• 多维数组赋初值:</strong></p>
<p>​ (1) 按行形式: <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a[<span class="number">4</span>][<span class="number">4</span>] = &#123;&#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>&#125;,&#123;<span class="number">5</span>,<span class="number">6</span>&#125;,&#123;<span class="number">8</span>&#125;,&#123;<span class="number">0</span>&#125;&#125;; <span class="comment">//每行初值不足补0</span></span><br><span class="line"><span class="keyword">int</span> b[][<span class="number">4</span>] = &#123;&#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>&#125;,&#123;<span class="number">5</span>,<span class="number">6</span>&#125;,&#123;<span class="number">8</span>&#125;,&#123;<span class="number">0</span>&#125;&#125;; <span class="comment">//第一维大小可以省略,由初值行数确定. 但第二维大小不可省略.</span></span><br></pre></td></tr></table></figure> ​ (2) 按整体形式: <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a[<span class="number">4</span>][<span class="number">4</span>] = &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">9</span>&#125;; <span class="comment">//数据按照内存中存放的顺序依次存储</span></span><br><span class="line"><span class="keyword">int</span> b[][<span class="number">4</span>] = &#123;<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">9</span>&#125;; <span class="comment">//第一维大小由初值个数所能构成的行数确定, 此处为2.</span></span><br></pre></td></tr></table></figure></p>
<h2 id="c风格字符串字符数组">C风格字符串(字符数组)</h2>
<p><strong>• C风格字符串:</strong> 用字符数组存放并用 '\0' 结束字符串, 用字符串首地址来使用字符串.</p>
<p><strong>• 赋初值:</strong> 可以按照普通字符数组赋初值的方式(不提倡, 繁琐且容易遗漏串结束标志<code>\0</code>), 通常按照赋字符串初值的方式. 见下例:</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">char</span> s1[<span class="number">10</span>] = &#123;<span class="string">'H'</span>,<span class="string">'e'</span>,<span class="string">'l'</span>,<span class="string">'l'</span>,<span class="string">'o'</span>&#125;;  <span class="comment">//遗漏了串结束标志</span></span><br><span class="line"><span class="keyword">char</span> s2[] = &#123;<span class="string">'H'</span>,<span class="string">'e'</span>,<span class="string">'l'</span>,<span class="string">'l'</span>,<span class="string">'o'</span>,<span class="string">'\0'</span>&#125;;  <span class="comment">//正确</span></span><br><span class="line"><span class="keyword">char</span> s3[] = <span class="string">"Hello"</span>;  <span class="comment">//与s2的赋值等价</span></span><br></pre></td></tr></table></figure>
<p><strong>• 字符串的输入输出:</strong> C风格字符串可以直接输入输出, 无需使用循环</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">char</span> s[<span class="number">80</span>];</span><br><span class="line"><span class="built_in">cin</span> &gt;&gt; s;  <span class="comment">//直接输入</span></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; s &lt;&lt; <span class="built_in">endl</span>;  <span class="comment">//直接输出</span></span><br></pre></td></tr></table></figure>
<p>几种输入方式的比较:</p>
<p>(定义<code>char ch; char s[80];</code>)</p>
<p><code>cin &gt;&gt; ch;</code> //输入一个字符到ch中, 跳过空格、跳格、回车等空白间隔符</p>
<p><code>ch = cin.get();</code> //等价于<code>cin.get(ch)</code>, 读取一个字符保存到ch中, 不跳过空白间隔符</p>
<p><code>cin &gt;&gt; s;</code> //输入一个单词到ch中, 遇到空白间隔符截断</p>
<p><code>cin.get(s, 80, '\n');</code> //第一个参数表示输入字符串到字符数组s中, 第二个参数表示此次输入保存的最大字符数(79个有效字符加一个串结束标志), 第三个参数(默认参数为<code>\n</code>,常常省略)表示遇到该字符结束输入, 不读取该字符, 并添加串结束标志. 注意: 如果前80个字符都没有回车字符, 那么将读取79个字符, 添加串结束标志, 并产生输入错误标志.</p>
<p><code>if(!cin) cin.clear();</code> //清除输入错误标志</p>
<p><code>cin.getline(s, 80, '\n');</code> //类似于<code>cin.get(s, 80, '\n')</code>, 只不过会读取回车字符<code>\n</code>然后丢弃.</p>
<p><strong>• 字符串的处理:</strong></p>
<ol type="1">
<li><p>利用串结束标志控制循环</p></li>
<li><p>使用库函数. 常用的字符串</p></li>
</ol>
<p><code>strlen(s);</code> //求字符串s的长度, 不含串结束标志. 英文: length</p>
<p><code>strcpy(s1, s2);</code> //将字符串s2复制到s1中. 英文: copy</p>
<p><code>strcmp(s1, s2);</code> //按字典序比较s1和s2. 相同时函数值为0, 不相同时比较ASCII码, s1&gt;s2时函数值为1, s1&lt;s2时函数值为-1. (注意, 大写字符的ASCII码小于小写字母的). 英文: compare</p>
<p><code>strcat(s1, s2);</code> //将字符串s2合并到s1的后面. 英文: catenate</p>
<p><code>strlwr(s);</code> //变为小写. 英文: lowercase</p>
<p><code>strupr(s);</code> //变为大写. 英文: uppercase</p>
<h2 id="常用数组算法">常用数组算法</h2>
<p>非常常用! 非常重要! 必须掌握!</p>
<p>为突出重点, 我们这里只列出核心代码</p>
<h3 id="有序插入">有序插入</h3>
<p>有序插入指在一个已经排序的数组中将数据插入, 使得到的数组保持已排序的状态. 此处我们以升序数组中有序插入为例.</p>
<p>假设已有定义<code>double d[20]; double x; int i,n=19;</code> 其中<code>double d[20]</code>中已有<code>n=19</code>个升序排列的数值. 我们要将<code>x</code>有序插入数组<code>d</code>.</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (i=n<span class="number">-1</span>; i&gt;=<span class="number">0</span> &amp;&amp; x&lt;d[i]; i--) &#123;  <span class="comment">//从后往前扫描数组直到插入位置, i始终处于空位的前一位</span></span><br><span class="line">    d[i+<span class="number">1</span>] = d[i];  <span class="comment">//扫描过的数据向后移动一位</span></span><br><span class="line">&#125;</span><br><span class="line">d[i+<span class="number">1</span>] = x; n++;  <span class="comment">// 插入数据, 数据个数增加1个</span></span><br></pre></td></tr></table></figure>
<h3 id="顺序查找">顺序查找</h3>
<p>较为简单. 假设已有定义<code>double d[20]; double x; int i,n=20;</code> 其中<code>double d[20]</code>中已有<code>n=20</code>个值. 我们在数组d中查找x. 只要</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; n; i++) <span class="keyword">if</span>(d[i] == x) <span class="keyword">break</span>;</span><br><span class="line"><span class="keyword">if</span> (i &lt; n) &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"查找的数是数组中第"</span> &lt;&lt; i+<span class="number">1</span> &lt;&lt; <span class="string">"个数"</span> &lt;&lt; <span class="built_in">endl</span>; &#125;</span><br><span class="line"><span class="keyword">else</span> &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"查找的数不在数组中"</span> &lt;&lt; <span class="built_in">endl</span>; &#125;</span><br></pre></td></tr></table></figure>
<p>即可</p>
<h3 id="折半查找">折半查找</h3>
<p>折半查找的前提是数组有序. 对于有序数组, 折半查找的效率大大高于顺序查找.</p>
<p>假设已有定义<code>double d[20]; double x; int i,n=20;</code> 其中<code>double d[20]</code>中已有<code>n=20</code>个值. 我们在数组d中查找x.</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> low, up;  <span class="comment">//定义low, up, 分别表示正在查找区间的上界和下界</span></span><br><span class="line"><span class="keyword">for</span> (low = <span class="number">0</span>, up = n<span class="number">-1</span>; low &lt;= up; ) &#123;</span><br><span class="line">    i = (low + up)/<span class="number">2</span>;  <span class="comment">//取中间数的下标i</span></span><br><span class="line">    <span class="keyword">if</span>(d[i] == x) <span class="keyword">break</span>;  <span class="comment">//找到就跳出循环</span></span><br><span class="line">    <span class="keyword">if</span>(x &lt; d[i]) &#123; up = i<span class="number">-1</span>; &#125;  <span class="comment">//x在d[low]~d[i-1]内</span></span><br><span class="line">    <span class="keyword">else</span> &#123; low = i+<span class="number">1</span>; &#125;  <span class="comment">//x在d[i+1]~d[up]内</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> (low &gt; up) &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"查找的数不在数组中"</span> &lt;&lt; <span class="built_in">endl</span>; &#125;</span><br><span class="line"><span class="keyword">else</span> &#123; <span class="built_in">cout</span> &lt;&lt; <span class="string">"查找的是数组中第"</span> &lt;&lt; i+<span class="number">1</span> &lt;&lt; <span class="string">"个数"</span> &lt;&lt; <span class="built_in">endl</span>; &#125;</span><br></pre></td></tr></table></figure>
<h3 id="选择法排序">选择法排序</h3>
<p>选择法排序(升序)的核心思想就是每次选择未处理的数中最小的, 放到左端已处理的数据之后.</p>
<p>假设已有定义<code>double d[100],t; int n,i,k,j;</code> 我们固定字母k用来记录下标.</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (i=<span class="number">0</span>; i&lt;n; i++) &#123;</span><br><span class="line">	<span class="keyword">for</span> (k=i, j=i+<span class="number">1</span>; j&lt;n; j++)  </span><br><span class="line">    	<span class="keyword">if</span>(d[j]&lt;d[k]) k = j;  <span class="comment">//找i到n-1范围内的最小值, 下标记录在k中</span></span><br><span class="line">	<span class="keyword">if</span>(k!=i) &#123; t = d[k]; d[k] = d[i]; d[i] = t; &#125;  <span class="comment">//若最小值不在d[i], 则交换到d[i]</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="冒泡法排序">冒泡法排序</h3>
<p>冒泡排序法(升序), 就是每次从前往后对相邻的数据进行比较, 若次序不正确, 则交换次序. 注意到最大的数据每次交换后都移至最后, 所以每次扫描的数据就要减少1个. 这样, 经过n-1次扫描, 排序就完成了.</p>
<p>具体实现是这样的: 假设已有定义<code>double d[100],t; int n,i,k;</code></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (k = n<span class="number">-1</span>; k&gt;<span class="number">0</span>; k--) &#123;</span><br><span class="line">	<span class="keyword">for</span> (i=<span class="number">0</span>; i&lt;k; i++)   <span class="comment">//扫描数组的前k+1项数据</span></span><br><span class="line">		<span class="keyword">if</span> (d[i]&gt;d[i+<span class="number">1</span>]) &#123; t = d[i]; d[i] = d[i+<span class="number">1</span>]; d[i+<span class="number">1</span>] = t; &#125;</span><br><span class="line">        <span class="comment">//相邻两项比较, 次序不对就换序</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

          
            <div class='article_footer'>
              
                
  
    
    


  

<section class="widget list references  desktop mobile">
  
  <header>
    
      <i class="fas fa-quote-left fa-fw" aria-hidden="true"></i><span class='name'>参考资料</span>
    
  </header>


  <div class='content'>
    <ul class="list entry navigation">
      
        <li><a class="flat-box" title="http://product.dangdang.com/25239691.html" href="http://product.dangdang.com/25239691.html"
          
          
          id="http:productdangdangcom25239691html"
          >
          <div class='name'>
            
            邵荣. C++程序设计(第二版)
          </div>
          
        </a></li>
      
    </ul>
  </div>
</section>



  

  
    
    



  

  
    
    

    <section class="widget copyright  desktop mobile">
        <div class='content'>
            
                <blockquote>
                    
                        
                                    <p>博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议。转载请保留原文链接和作者。</p>

                                        
                                            
                </blockquote>
                
        </div>
    </section>
  

  


              
            </div>
          
        </div>
        
          


  <section class='meta' id="footer-meta">
    <div class='new-meta-box'>
      
        
          <div class="new-meta-item date" itemprop="dateUpdated" datetime="2020-08-22T19:36:36+08:00">
  <a class='notlink'>
    <i class="fas fa-edit fa-fw" aria-hidden="true"></i>
    <p>更新于：2020年8月22日 19:36</p>
  </a>
</div>

        
      
        
          
  
  <div class="new-meta-item meta-tags"><a class="tag" href="/junblog/tags/C/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>C++</p></a></div>


        
      
        
          
  <div class="new-meta-item share -mob-share-list">
  <div class="-mob-share-list share-body">
    
      
        <a class="-mob-share-qq" title="" rel="external nofollow noopener noreferrer"
          
          href="http://connect.qq.com/widget/shareqq/index.html?url=https://heliumhe.gitee.io/2020/08/16/C++%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E5%9F%BA%E7%A1%80(4)%20-%20%E5%A4%8D%E5%90%88%E7%B1%BB%E5%9E%8B%E6%95%B0%E6%8D%AE_%E6%95%B0%E7%BB%84/&title=C++程序设计基础(4) - 复合类型数据：数组 - Jun's Blog&summary=介绍数组和C风格字符串的处理, 以及一些十分常用的数组算法."
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/logo/128/qq.png">
          
        </a>
      
    
      
        <a class="-mob-share-qzone" title="" rel="external nofollow noopener noreferrer"
          
          href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https://heliumhe.gitee.io/2020/08/16/C++%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E5%9F%BA%E7%A1%80(4)%20-%20%E5%A4%8D%E5%90%88%E7%B1%BB%E5%9E%8B%E6%95%B0%E6%8D%AE_%E6%95%B0%E7%BB%84/&title=C++程序设计基础(4) - 复合类型数据：数组 - Jun's Blog&summary=介绍数组和C风格字符串的处理, 以及一些十分常用的数组算法."
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/logo/128/qzone.png">
          
        </a>
      
    
      
        <a class="-mob-share-weibo" title="" rel="external nofollow noopener noreferrer"
          
          href="http://service.weibo.com/share/share.php?url=https://heliumhe.gitee.io/2020/08/16/C++%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E5%9F%BA%E7%A1%80(4)%20-%20%E5%A4%8D%E5%90%88%E7%B1%BB%E5%9E%8B%E6%95%B0%E6%8D%AE_%E6%95%B0%E7%BB%84/&title=C++程序设计基础(4) - 复合类型数据：数组 - Jun's Blog&summary=介绍数组和C风格字符串的处理, 以及一些十分常用的数组算法."
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/logo/128/weibo.png">
          
        </a>
      
    
      
        
        <div class='hoverbox'>
          <a><img src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/logo/128/wechat.png"></a>
          <div class='target'>
            <img src="">
          </div>
        </div>
      
    
  </div>
</div>



        
      
    </div>
  </section>


        
        
          <div class="prev-next">
            
              <a class='prev' href='/junblog/2020/08/20/C++%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E5%9F%BA%E7%A1%80(5)%20-%20%E5%A4%8D%E5%90%88%E7%B1%BB%E5%9E%8B%E6%95%B0%E6%8D%AE_%E6%8C%87%E9%92%88%E4%B8%8E%E5%BC%95%E7%94%A8%E5%88%9D%E6%AD%A5/'>
                <p class='title'><i class="fas fa-chevron-left" aria-hidden="true"></i>C++程序设计基础(5) - 复合类型数据：指针与引用初步</p>
                <p class='content'>指针和引用类型的初步介绍, 更深入的内容留到后面再讲.

指针
指针就是地址. 所有的变量都在内存中有一个地址, 通过地址可以使用变量, 我们就把这些地址形象地称为指向变量的指针.
指针...</p>
              </a>
            
            
              <a class='next' href='/junblog/2020/08/15/C++%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E5%9F%BA%E7%A1%80(3)%20-%20%E7%BB%93%E6%9E%84%E5%8C%96%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/'>
                <p class='title'>C++程序设计基础(3) - 结构化程序设计<i class="fas fa-chevron-right" aria-hidden="true"></i></p>
                <p class='content'>介绍两种基本的结构: 选择结构与循环结构

语句
语句是C++程序的基本执行单位. 在C++中, 一个语句后面加分号表示语句的结束.
C++中的语句分为单语句、复合语句和结构性语句.
...</p>
              </a>
            
          </div>
        
      </section>
    </article>
  

  
    <!-- 显示推荐文章和评论 -->



  <article class="post white-box reveal comments blur">
    <section class="article typo">
      <p ct><i class='fas fa-comments'></i> 评论</p>
      
        <p cst>读者们可以在此处进行交流</p>
      
      
      
      
      
      
        <section id="comments">
          <div id="valine_container" class="valine_thread">
            <i class="fas fa-cog fa-spin fa-fw fa-2x"></i>
          </div>
        </section>
      
      
    </section>
  </article>


  




<!-- 根据页面mathjax变量决定是否加载MathJax数学公式js -->



  <script>
    window.subData = {
      title: 'C++程序设计基础(4) - 复合类型数据：数组',
      tools: true
    }
  </script>


</div>
<aside class='l_side'>
  
  
    
    



  <section class="widget toc-wrapper blur desktop mobile" id="toc-div" >
    
  <header>
    
      <i class="fas fa-list fa-fw" aria-hidden="true"></i><span class='name'>本文目录</span>
    
  </header>


    <div class='content'>
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一维数组"><span class="toc-number">1.</span> <span class="toc-text">一维数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#多维数组"><span class="toc-number">2.</span> <span class="toc-text">多维数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#c风格字符串字符数组"><span class="toc-number">3.</span> <span class="toc-text">C风格字符串(字符数组)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#常用数组算法"><span class="toc-number">4.</span> <span class="toc-text">常用数组算法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#有序插入"><span class="toc-number">4.1.</span> <span class="toc-text">有序插入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#顺序查找"><span class="toc-number">4.2.</span> <span class="toc-text">顺序查找</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#折半查找"><span class="toc-number">4.3.</span> <span class="toc-text">折半查找</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#选择法排序"><span class="toc-number">4.4.</span> <span class="toc-text">选择法排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#冒泡法排序"><span class="toc-number">4.5.</span> <span class="toc-text">冒泡法排序</span></a></li></ol></li></ol>
    </div>
  </section>


  


</aside>


  
  <footer class="clearfix">
    <br><br>
    
      
        <div class="aplayer-container">
          


        </div>
      
    
      
        <br>
        <div class="social-wrapper">
          
            
              <a href="/junblog/atom.xml"
                class="social fas fa-rss flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
              </a>
            
          
            
              <a href="mailto:hejunyuan02@126.com"
                class="social fas fa-envelope flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
              </a>
            
          
            
              <a href="https://music.163.com/#/user/home?id=63035382"
                class="social fas fa-headphones-alt flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
              </a>
            
          
        </div>
      
    
      
        本站使用
        <a href="https://volantis.js.org/" target="_blank" class="codename">Volantis</a>
        作为主题，总访问量为
          <span id="busuanzi_value_site_pv"><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span>
          次
        
      
    
      
        <div class='copyright'>
        <p><a href="https://junyuanhe.github.io/" target="_blank" rel="noopener">Copyright © 2019-2020 Jun</a></p>

        </div>
      
    
  </footer>

<script>setLoadingBarProgress(80);</script>


      <script>setLoadingBarProgress(60);</script>
    </div>
    <a class="s-top fas fa-arrow-up fa-fw" href='javascript:void(0)'></a>
  </div>
  
<script src="https://cdn.jsdelivr.net/npm/jquery@3.4/dist/jquery.min.js"></script>


  <script>
    
    var SEARCH_SERVICE = "hexo" || "hexo";
    var ROOT = "/junblog/" || "/";
    if (!ROOT.endsWith('/')) ROOT += '/';
  </script>





  <script async src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-volantis@2/js/instant_page.js" type="module" defer integrity="sha384-OeDn4XE77tdHo8pGtE1apMPmAipjoxUQ++eeJa6EtJCfHlvijigWiJpD7VDPWXV1"></script>


  <script src="https://cdn.jsdelivr.net/npm/scrollreveal@4.0.6/dist/scrollreveal.min.js"></script>
  <script type="text/javascript">
    $(function() {
      ScrollReveal().reveal('.l_main .reveal', {
        distance: '8px',
        duration: '800',
        interval: '100',
        scale: '1'
      });
    });
  </script>


  
<script src="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.js"></script>

  <script type="text/javascript">
    $(function() {
      Waves.attach('.flat-btn', ['waves-button']);
      Waves.attach('.float-btn', ['waves-button', 'waves-float']);
      Waves.attach('.float-btn-light', ['waves-button', 'waves-float', 'waves-light']);
      Waves.attach('.flat-box', ['waves-block']);
      Waves.attach('.float-box', ['waves-block', 'waves-float']);
      Waves.attach('.waves-image');
      Waves.init();
    });
  </script>


  <script defer src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-busuanzi@2.3/js/busuanzi.pure.mini.js"></script>



  
  
  
    
<script src="https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js"></script>

    <script type="text/javascript">
      $(function(){
        var imgs=["https://cdn.jsdelivr.net/gh/xaoxuu/cdn-wallpaper/abstract/41F215B9-261F-48B4-80B5-4E86E165259E.jpeg", "https://cdn.jsdelivr.net/gh/xaoxuu/cdn-wallpaper/abstract/BBC19066-E176-47C2-9D22-48C81EE5DF6B.jpeg", "https://cdn.jsdelivr.net/gh/xaoxuu/cdn-wallpaper/abstract/B18FCBB3-67FD-48CC-B4F3-457BA145F17A.jpeg", "https://cdn.jsdelivr.net/gh/xaoxuu/cdn-wallpaper/abstract/67239FBB-E15D-4F4F-8EE8-0F1C9F3C4E7C.jpeg"];
        if ('true' == 'true') {
          function shuffle(arr){
            /*From countercurrent-time*/
            var n = arr.length;
            while(n--) {
              var index = Math.floor(Math.random() * n);
              var temp = arr[index];
              arr[index] = arr[n];
              arr[n] = temp;
            }
          }
          shuffle(imgs);
        }
        if ('.cover') {
          $('.cover').backstretch(
            imgs,
          {
            duration: "20000",
            fade: "1500"
          });
        } else {
          $.backstretch(
            imgs,
          {
            duration: "20000",
            fade: "1500"
          });
        }
      });
    </script>
  











  
    
<script src="/junblog/js/valine.js"></script>

  
  <script>
  var GUEST_INFO = ['nick','mail','link'];
  var meta = 'nick,mail'.split(',').filter(function(item){
    return GUEST_INFO.indexOf(item) > -1
  });
  var REQUIRED_FIELDS = ['nick','mail','link'];
  var requiredFields = 'nick,mail'.split(',').filter(function(item){
    return REQUIRED_FIELDS.indexOf(item) > -1
  });
  var valine = new Valine();
  function emoji(path, idx, ext) {
      return path + "/" + path + "-" + idx + "." + ext;
  }
  var emojiMaps = {};
  for (var i = 1; i <= 54; i++) {
    emojiMaps['tieba-' + i] = emoji('tieba', i, 'png');
  }
  for (var i = 1; i <= 101; i++) {
    emojiMaps['qq-' + i] = emoji('qq', i, 'gif');
  }
  for (var i = 1; i <= 116; i++) {
    emojiMaps['aru-' + i] = emoji('aru', i, 'gif');
  }
  for (var i = 1; i <= 125; i++) {
    emojiMaps['twemoji-' + i] = emoji('twemoji', i, 'png');
  }
  for (var i = 1; i <= 4; i++) {
    emojiMaps['weibo-' + i] = emoji('weibo', i, 'png');
  }
  valine.init({
    el: '#valine_container',
    meta: meta,
    
    appId: "GbPm6UIzHrGduLaANgBIdhkf-gzGzoHsz",
    appKey: "SFuacIL4IJSnGk9TDX46eb0Y",
    placeholder: "快来评论吧~",
    pageSize:'10',
    avatar:'robohash',
    lang:'zh-cn',
    visitor: 'true',
    highlight: 'true',
    mathJax: 'true',
    enableQQ: 'true',
    requiredFields: requiredFields,
    emojiCDN: 'https://cdn.jsdelivr.net/gh/xaoxuu/cdn-assets/emoji/valine/',
    emojiMaps: emojiMaps
  })
  </script>





  
<script src="/junblog/js/app.js"></script>



  
<script src="https://cdn.jsdelivr.net/gh/xaoxuu/cdn-volantis@2.6.5/js/search.js"></script>







<!-- 复制 -->

  <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="fas fa-copy"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('fa-copy');
        $icon.addClass('fa-check-circle');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('fa-check-circle');
          $icon.addClass('fa-copy');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('fa-copy');
        $icon.addClass('fa-times-circle');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('fa-times-circle');
          $icon.addClass('fa-copy');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>




<!-- fancybox -->
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>
<script>
  function pjax_fancybox() {
    $(".article-entry").find("img").not('.inline').not('a img').each(function () { //渲染 fancybox
      var element = document.createElement("a"); // a 标签
      $(element).attr("pjax-fancybox", "");  // 过滤 pjax
      $(element).attr("href", $(this).attr("src"));
      if ($(this).attr("data-original")) {
        $(element).attr("href", $(this).attr("data-original"));
      }
      $(element).attr("data-fancybox", "images");
      var caption = "";   // 描述信息
      if ($(this).attr('alt')) {  // 标准 markdown 描述信息
        $(element).attr('data-caption', $(this).attr('alt'));
        caption = $(this).attr('alt');
      }
      var div = document.createElement("div");
      $(div).addClass("fancybox");
      $(this).wrap(div); // 最外层套 div ，其实主要作用还是 class 样式
      var span = document.createElement("span");
      $(span).addClass("image-caption");
      $(span).text(caption); // 加描述
      $(this).after(span);  // 再套一层描述
      $(this).wrap(element);  // 最后套 a 标签
    })
    $(".article-entry").find("img").fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: false,
      closeClick: true,
      helpers: {
        overlay: {closeClick: true}
      },
      buttons: [
        "zoom",
        "close"
      ]
    });
  };
  $(function () {
    pjax_fancybox();
  });
</script>





  <script>setLoadingBarProgress(100);</script>
</body>
</html>
